package com.zndroid.logcat.displayer;

import com.zndroid.logcat.core.LogInfo;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * Created by lzy on 2021/1/21.
 *
 * 文件可能很大哟
 */
public class LogSaveTask implements Runnable {
    private File saveFile;
    private List<LogInfo> dataList;

    public LogSaveTask(File file, List<LogInfo> dataList) {
        this.saveFile = file;
        this.dataList = dataList;
    }

    @Override
    public void run() {
        if (null == dataList || dataList.size() <= 0) {return;}

        BufferedWriter bufferedWriter = null;
        try {
            if (saveFile.isFile() && saveFile.exists()) {
                saveFile.delete();
            }
            saveFile.createNewFile();
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));

            synchronized(LogSaveTask.class) {
                for (LogInfo info : dataList) {
                    bufferedWriter.write(info.getOrigin());
                    bufferedWriter.newLine();
                }

                bufferedWriter.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(bufferedWriter);
        }

    }

    private void close(Closeable...closes){
        for(Closeable close : closes){
            if(null!=close){
                try{
                    close.close();
                }catch (IOException ignored){
                    //ignore
                }
            }
        }
    }
}
